object ClosuresDemo extends App {
  // 1. 资源使用追踪：使用闭包记录使用次数
  def createResourceTracker(resourceId: String): (Double) => (String, Int, Double) = {
    // 这些变量在闭包中被捕获
    var usageCount = 0    // 使用次数
    var totalDuration = 0.0  // 总使用时长（小时）

    // 这个函数会捕获并修改外部变量，形成闭包
    (duration: Double) => {
      usageCount += 1
      totalDuration += duration
      (resourceId, usageCount, totalDuration)
    }
  }

  // 2. 创建不同资源的追踪器
  val classroomTracker = createResourceTracker("R101教室")
  val projectorTracker = createResourceTracker("P001投影仪")

  // 3. 记录资源使用
  println("=== 资源使用记录 ===")
  println(classroomTracker(2.0))  // 使用2小时
  println(projectorTracker(1.5))  // 使用1.5小时
  println(classroomTracker(3.0))  // 再使用3小时
  println(projectorTracker(2.0))  // 再使用2小时
  println(classroomTracker(2.0))  // 再使用2小时
  println(projectorTracker(1.5))  // 再使用1.5小时

  // 4. 闭包实现累加器
  def createAccumulator(initialValue: Double): (Double) => Double = {
    var total = initialValue
    (amount: Double) => {
      total += amount
      total
    }
  }

  // 创建学生出勤累加器
  val attendanceAccumulator = createAccumulator(0)

  println("\n=== 学生出勤统计 ===")
  println(s"第1周出勤：${attendanceAccumulator(32)} 人")
  println(s"第2周出勤：${attendanceAccumulator(30)} 人")
  println(s"第3周出勤：${attendanceAccumulator(31)} 人")
  println(s"总出勤：${attendanceAccumulator(0)} 人")  // 不添加，只查询

  // 5. 带状态的闭包：成绩等级统计
  def createGradeCounter(passLine: Double, goodLine: Double, excellentLine: Double): (Double) => Map[String, Int] = {
    var counts = Map(
      "不及格" -> 0,
      "及格" -> 0,
      "良好" -> 0,
      "优秀" -> 0
    )

    (score: Double) => {
      val grade =
        if (score >= excellentLine) "优秀"
        else if (score >= goodLine) "良好"
        else if (score >= passLine) "及格"
        else "不及格"

      counts = counts + (grade -> (counts(grade) + 1))
      counts
    }
  }

  // 创建严格标准的成绩计数器
  val strictGradeCounter = createGradeCounter(60, 80, 90)

  println("\n=== 成绩等级统计 ===")
  val scores = List(95, 78, 56, 88, 90, 65, 72, 45, 80)
  scores.foreach { score =>
    val result = strictGradeCounter(score)
    println(s"输入 $score 分后：$result")
  }

  // 6. 闭包捕获可变状态
  def createUniqueIdGenerator(prefix: String): () => String = {
    var counter = 0
    () => {
      counter += 1
      s"$prefix-$counter"
    }
  }

  val studentIdGenerator = createUniqueIdGenerator("S")
  val courseIdGenerator = createUniqueIdGenerator("C")

  println("\n=== 唯一ID生成 ===")
  println(studentIdGenerator())
  println(studentIdGenerator())
  println(studentIdGenerator())
  println(courseIdGenerator())
  println(studentIdGenerator())
  println(courseIdGenerator())
}
//10.1106【动手练习3】：实现校园资源使用追踪功能